package com.example.demo.filter;

import com.example.demo.pojo.Result;
import com.example.demo.service.LoginRegisterservice;
import com.example.demo.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter(urlPatterns = {"/ResultProject/*"})
public class Nresultprojectfilter implements Filter {
    @Autowired
    LoginRegisterservice loginRegisterservice;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        String jwt=req.getHeader("token");
        Claims claims= JwtUtils.parseJWT(jwt);
        String username= (String) claims.get("userName");
        String post=loginRegisterservice.selectpost(username);
        if(post=="管理员"){
            filterChain.doFilter(req,resp);
            return;
        }
        if (post == "医生") {
            filterChain.doFilter(req,resp);
            return;

        } else {
//           Result erro=Result.error("权限不足，请联系管理员");
//           String msg= JSONObject.toJSONString(erro);
//           resp.getWriter().write(msg);
//           return;
//
            Result erro = Result.error("权限不足，请联系管理员");
// 创建ObjectMapper实例
            ObjectMapper objectMapper = new ObjectMapper();

// 将Result对象序列化为JSON字符串
            String json = objectMapper.writeValueAsString(erro);
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(json);

        }

    }

}
